package vitaliy.bondar.diamondcave;

import org.andengine.entity.Entity;
import org.andengine.entity.scene.ITouchArea;
import org.andengine.entity.sprite.Sprite;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.vbo.VertexBufferObjectManager;

interface OnToggledListener {
    void onToggled(boolean state);
}

public class CheckBox extends Entity implements ITouchArea
{
	private boolean m_isChecked;
	private final Sprite m_check;
	private final Sprite m_box;
	private final OnToggledListener m_listener;
	
	public CheckBox(final float x, final float y, final VertexBufferObjectManager vbom, 
			final OnToggledListener listener) 
	{
		m_listener = listener;
		m_isChecked = false;
		m_box = new Sprite(x, y, ResourcesManager.getInstance().checkbox_unchecked_region, vbom);
		m_check = new Sprite(x, y, ResourcesManager.getInstance().checkbox_checked_region, vbom);
		this.attachChild(m_box);
		this.attachChild(m_check);
		
		m_check.setVisible(m_isChecked);
	}

	public final boolean isChecked()
	{
		return m_isChecked;
	}
	
	public void setChecked(boolean set)
	{
		m_isChecked = set;
		m_check.setVisible(m_isChecked);
		m_listener.onToggled(m_isChecked);
	}
	
	public void setSize(float width, float height)
	{
	    m_box.setSize(width, height);
	    m_check.setSize(width, height);
	}

	@Override
	public boolean contains(float x, float y) 
	{
		return m_box.contains(x, y);
	}

	@Override
	public boolean onAreaTouched(TouchEvent event, float x, float y) 
	{
		if (event.isActionDown())
		{
			this.setChecked(!m_isChecked);
		}
		return true;
	}
}
